import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    cartItems: JSON.parse(localStorage.getItem('carts')) || []
  },
  mutations: {
    ADD_CART(state, item) {
      console.log(item)
      var flag = false
      state.cartItems.forEach((ele) => {
        if (item.id === ele.id) {
          console.log("存在", item)
          ele.count++
          flag = true
        }
      })
      if (!flag) {
        console.log("不存在", item)
        item.count = 1
        item.checked = false
        state.cartItems.push(item)
      }
      localStorage.setItem('carts',JSON.stringify([...state.cartItems]))
    }
  },
  actions: {
    ADD_CART(context,item) {
      context.commit('ADD_CART',item)
    }
  },
  modules: {
  }
})
